import { BlockPermutation, world } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Vector3Utils } from "@sapi-game/utils";
import { WereWolfModule } from "@/werewolf/module";
import { WereWolfRole, WereWolfStatus } from "@/werewolf/player";

interface chestData {
    pos: [number, number, number];
    direction: "east" | "north" | "south" | "west";
}

const chests: chestData[] = [
    { pos: [-75, -56, -103], direction: "east" },
    { pos: [-65, -56, -121], direction: "east" },
    { pos: [-51, -56, -128], direction: "south" },
    { pos: [-35, -56, -125], direction: "west" },
    { pos: [-27, -56, -107], direction: "west" },
    { pos: [-34, -56, -90], direction: "west" },
    { pos: [-49, -56, -84], direction: "north" },
    { pos: [-65, -56, -87], direction: "east" },
];

export class WereWolfChestLoader extends WereWolfModule.Component {
    override onAttach(): void {}

    resetChest() {
        chests.forEach((t) => {
            const loc = Vector3Utils.fromArray(t.pos);
            world.structureManager.place(
                "狼人杀_箱子",
                Dimensions.Overworld,
                loc
            );
            Dimensions.Overworld.getBlock(loc)?.setPermutation(
                BlockPermutation.resolve("chest", {
                    "minecraft:cardinal_direction": t.direction,
                })
            );
        });
    }

    loadWolfChest() {
        const wolfs = this.context.players.filter(
            (p) =>
                p.status == WereWolfStatus.Live &&
                p.role == WereWolfRole.Werewolf
        );
        wolfs.forEach((p) => {
            const chest = chests![p.no - 1];
            if (chest) {
                const loc = Vector3Utils.fromArray(chest.pos);
                world.structureManager.place(
                    "狼人杀_狼箱子",
                    Dimensions.Overworld,
                    loc
                );
                Dimensions.Overworld.getBlock(loc)?.setPermutation(
                    BlockPermutation.resolve("chest", {
                        "minecraft:cardinal_direction": chest.direction,
                    })
                );
            }
        });
        wolfs.forEach((p) => {
            p.sendMessage("§a你的箱子刷新了");
        });
    }
}
